<template>
  <div class="enterprise-container">
    <!-- 页面头部 -->
    <div class="header">
      <el-page-header
        @back="$router.back()"
        :content="id ? '编辑企业信息' : '新增企业信息'"
        title="返回"
      >
      </el-page-header>
    </div>

    <!-- 企业信息 -->
    <div class="enterprise-info">
      <h3>企业信息</h3>
      <el-form
        :model="enterpriseForm"
        label-width="120px"
        class="form-container"
        :rules="enterpriseRules"
        ref="enterpriseFormRef"
      >
        <!-- 第一列 -->
        <div class="form-row">
          <el-form-item label="企业名称" prop="name">
            <el-input
              v-model="enterpriseForm.name"
              placeholder="请输入企业名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="法人" prop="legalPerson">
            <el-input
              v-model="enterpriseForm.legalPerson"
              placeholder="请输入法人姓名"
            ></el-input>
          </el-form-item>
        </div>
        <!-- 第二列 -->
        <div class="form-row">
          <el-form-item label="注册地址" prop="registeredAddress">
            <el-input
              v-model="enterpriseForm.registeredAddress"
              placeholder="请输入注册地址"
            ></el-input>
          </el-form-item>
          <el-form-item label="所在行业" prop="industryCode">
            <!-- <el-input
              v-model="enterpriseForm.industryCode"
              placeholder="请输入所在行业"
            ></el-input> -->
            <el-select
              v-model="enterpriseForm.industryCode"
              placeholder="请选择所在行业"
            >
              <el-option
                v-for="item in list"
                :key="item.industryCode"
                :label="item.industryName"
                :value="item.industryCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <!-- 第三列 -->
        <div class="form-row">
          <el-form-item label="营业执照" prop="businessLicenseUrl">
            <el-upload
              class="upload-demo"
              action="#"
              :http-request="uploadImage"
              :before-upload="beforeUpload"
              ref="uploadRef"
              :on-remove="handleRemove"
            >
              <el-button type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">支持 jpg/png格式</div>
            </el-upload>
            <img
              :src="this.enterpriseForm.businessLicenseUrl"
              alt=""
              style="width: 100px"
            />
          </el-form-item>
        </div>
      </el-form>
    </div>

    <!-- 联系人信息 -->
    <div class="contact-info">
      <h3>联系人信息</h3>
      <el-form
        :model="contactForm"
        label-width="120px"
        class="form-container"
        :rules="contactRules"
        ref="contactFormRef"
      >
        <!-- 联系人和电话 -->
        <div class="form-row">
          <el-form-item label="企业联系人" prop="contact">
            <el-input
              v-model="contactForm.contact"
              placeholder="请输入联系人姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="contactNumber">
            <el-input
              v-model="contactForm.contactNumber"
              placeholder="请输入联系电话"
            ></el-input>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <!-- 提交与重置按钮 -->
    <div class="form-actions">
      <el-button type="primary" @click="submitForms">确定</el-button>
      <el-button @click="resetForms">重置</el-button>
    </div>
  </div>
</template>

<script>
import {
  getIndustryListAPI,
  addEnterpriseAPI,
  getEnterpriseDetailAPI,
  updateEnterpriseDetailAPI,
} from "@/api/enterprise";
import { uploadFileAPI } from "@/api/common";
export default {
  data() {
    const initialEnterpriseForm = {
      name: "", // 企业名称
      legalPerson: "", // 法人
      registeredAddress: "", // 注册地址
      industryCode: "", // 所在行业
      businessLicenseUrl: "", // 营业执照
      businessLicenseId: "", //上传文件id
    };
    const initialContactForm = {
      contact: "", // 联系人
      contactNumber: "", // 联系电话
    };
    return {
      enterpriseForm: { ...initialEnterpriseForm },
      contactForm: { ...initialContactForm },
      enterpriseRules: {
        name: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
        legalPerson: [
          { required: true, message: "请输入法人姓名", trigger: "blur" },
        ],
        registeredAddress: [
          { required: true, message: "请输入注册地址", trigger: "blur" },
        ],
        industryCode: [
          { required: true, message: "请输入所在行业", trigger: "change" },
        ],
        businessLicenseUrl: [
          { required: true, message: "请上传营业执照", trigger: "blur" },
        ],
      },
      contactRules: {
        contact: [
          { required: true, message: "请输入联系人姓名", trigger: "blur" },
        ],
        contactNumber: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
        ],
      },

      list: [], // 企业所属行业列表
    };
  },
  computed: {
    id() {
      return this.$route.query.id || null; // 确保当没有 id 时返回 null
    },
  },
  created() {
    this.getIndustryList();
    if (this.id) {
      this.getEnterpriseDetail();
    }
  },
  methods: {
    // 二次封装获取所在行业列表
    async getIndustryList() {
      const res = await getIndustryListAPI();
      this.list = res.data;
    },
    // 文件自定义上传
    async uploadImage({ file }) {
      const formData = new FormData();
      formData.append("file", file);
      formData.append("type", 1);
      const res = await uploadFileAPI(formData);
      this.enterpriseForm.businessLicenseUrl = res.data.url;
      this.enterpriseForm.businessLicenseId = res.data.id;
      this.$refs.enterpriseFormRef.validateField("businessLicenseUrl");
    },
    // beforeUpload上传之前校验
    beforeUpload(file) {
      const imageType = [
        "image/jpeg",
        "image/ipg",
        "image/png",
        "image/gif",
        "image/svg+xml",
        "image/bmp",
      ];
      if (!imageType.includes(file.type)) {
        this.$message.error("图片格式不正确");
        return false;
      }
      if (file.size / 1024 / 1024 > 5) {
        this.$message.error("图片大小不能超过5M");
        return false;
      }
    },
    // 移除文件
    handleRemove() {
      this.enterpriseForm.businessLicenseUrl = "";
      this.enterpriseForm.businessLicenseId = "";
      this.$message.success("移除成功");
    },
    // 确定校验表单
    submitForms() {
      this.$refs.enterpriseFormRef.validate((valid1) => {
        if (valid1) {
          this.$refs.contactFormRef.validate(async (valid2) => {
            if (valid2) {
              // 如果两个表单都验证成功，则执行提交逻辑
              if (this.id) {
                //编辑接口
                updateEnterpriseDetailAPI({
                  ...this.enterpriseForm,
                  ...this.contactForm,
                  id: this.id,
                });
              } else {
                //新增接口
                await addEnterpriseAPI({
                  ...this.enterpriseForm,
                  ...this.contactForm,
                });
              }
              this.$message.success(this.id ? "更新成功" : "新增成功");
              this.$router.go(-1);
            }
          });
        }
      });
    },
    // 重置
    resetForms() {
      this.enterpriseForm = { ...this.initialEnterpriseForm };
      this.contactForm = { ...this.initialContactForm };
      this.$refs.uploadRef.clearFiles();
    },
    // 园区管理-查看企业
    async getEnterpriseDetail() {
      const res = await getEnterpriseDetailAPI(this.id);
      const {
        name,
        legalPerson,
        registeredAddress,
        industryCode,
        businessLicenseId,
        businessLicenseUrl,
      } = res.data;
      this.enterpriseForm = {
        name,
        legalPerson,
        registeredAddress,
        industryCode,
        businessLicenseId,
        businessLicenseUrl,
      };
      const { contact, contactNumber } = res.data;
      this.contactForm = { contact, contactNumber };
    },
  },
};
</script>

<style scoped>
.enterprise-container {
  max-width: 1600px;
  margin: 100px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 页面头部样式 */
.header {
  display: flex;
  align-items: center;
  margin-bottom: 40px;
}

/* 表单样式 */
.form-container {
  margin-bottom: 30px;
}
.form-row {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}
.form-row > .el-form-item {
  flex: 1;
}

/* 信息区样式 */
.enterprise-info,
.contact-info {
  padding: 20px;
  margin-top: 30px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #f9f9f9;
}
.enterprise-info h3,
.contact-info h3 {
  margin: 0 0 10px;
  font-size: 18px;
}
/* 按钮样式 */
.form-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}
</style>
